package cn.com.infohold.smartcity.recceiver;

import android.content.Context;
import android.content.Intent;
import android.text.TextUtils;

import java.io.Serializable;

import cn.com.infohold.smartcity.activity.MessageDetailActivity;
import cn.com.infohold.smartcity.api.bean.Message;
import cn.com.infohold.smartcity.parent.ParentReceiver;
import cn.com.infohold.smartcity.utils.PageUtils;
import library.utils.Logger;
import library.utils.Utils;


/*
    <receiver android:name="cn.com.infohold.smartcity.broadcast.ReceiverApp">
        <intent-filter>
            <action android:name="receiver.app.start" />
         </intent-filter>
    </receiver>
 */
public class ReceiverApp extends ParentReceiver {

    public static final String ACTION_LAUNCH = "receiver.action.launch";
    public static final String ACTION_GOTO = "receiver.action.goto";


    @Override
    public void onReceive(Context context, Intent intent) {

        final String action = intent.getAction();
        final String packageName = intent.getStringExtra("PackageName");
        if (TextUtils.isEmpty(packageName) || !context.getPackageName().equals(packageName)) {
            return;
        }

        switch (action) {
            case ACTION_LAUNCH:
                launchApp(context);
                break;
            case ACTION_GOTO:
                try {
                    Serializable data = intent.getSerializableExtra(Serializable.class.getName());
                    if (data instanceof Message)
                        PageUtils.jumpToPageOrPend(context, MessageDetailActivity.class, data);
                } catch (Exception e) {
                    Logger.debug(e);
                }
                break;
            default:
                break;
        }
    }

    private static void launchApp(Context context) {
        if (!Utils.isActivityRunning(context)
                || Utils.isApplicationRunningInBackground(context))
            Utils.startAPP(context);
    }
}